#coding=utf-8

import os, re
from ripper.handler.Policy import torrentProxyPolicy
from ripper.core.Utils import getId, enable_proxy, disable_proxy #@UnresolvedImport
from ripper.core.Utils import clear_url
from urllib import urlopen, urlencode


CODE_MAP = {
            'http://www.haoseed.com/' : 'ref',
            'http://www.jandown.com/' : 'code',
            'http://www.mimima.com/' : 'code',
           }
URL_PATTERNS = [
                r'.*?(http\://www[0-9]*\.jandown.com/link\.php\?ref=[a-z,A-Z,0-9]{10})',
                r'.*?(http\://www[0-9]*\.mimima.com/link\.php\?ref=[a-z,A-Z,0-9]{10})',
                r'.*?(http\://www[0-9]*\.haoseed.com/ref\.php\?ref=[a-z,A-Z,0-9]{10})',
                
                ]

def info(msg):
    print msg
    
# 正则表达式匹配种子地址
def reFindUrl(url):
    url = url.replace(' ','')
    url = url.replace('@','')
    for pattern in URL_PATTERNS:
        for m in re.findall(pattern, url):
            return m
    return None
    
def readConfig(name):
    if name == 'httpproxy':
        return ''

def canDownload(turl):
    if turl == None or len(turl) < 45:
        return False
    if turl.lower().find('haoseed') != -1:
            return True
    if turl.lower().find('jandown') != -1 or turl.lower().find('mimima') != -1:
#    if turl.lower().find('jandown') != -1 :
        return True
    return False    

class TorrentDownloader:
    def __init__(self,torrentUrl,proxy={}):
        # 正则表达式匹配种子地址
        clearedUrl = reFindUrl(torrentUrl)
        if clearedUrl == None:
            torrentUrl = clear_url(torrentUrl)
        else:
            torrentUrl = clearedUrl
        self.proxy = proxy
        self.torrentUrl = torrentUrl
        self.siteName = self.getSiteName(self.torrentUrl)
        self.fetchUrl = self.getFetchUrl(self.torrentUrl)
        self.code = self.getCode(self.torrentUrl)
        self.postName = CODE_MAP[self.siteName] # form input for mimima and jandown
        
    def download(self, dirName):
        try:
            # check proxy policy for the site
            if torrentProxyPolicy.has_key(self.siteName):
                if torrentProxyPolicy[self.siteName] == True:
                    info('Using proxy for '+self.siteName)
                    #self.proxy['http'] = readConfig('httpproxy')
                    enable_proxy()
            conn = urlopen(self.fetchUrl,urlencode({self.postName:self.code}))
#            conn = urlopen(self.fetchUrl,urlencode({self.postName:self.code}),\
#                                proxies=self.proxy)
            filename = getDownloadedFileName()                    
            f = os.path.join(dirName , filename)
            df = open(f,'wb')
            df.write(conn.read())
            df.close()
            conn.close()
            return filename, os.path.getsize(f)
        except Exception, ex:
            print ex
        finally:
            disable_proxy()    
            
    def getCode(self,turl):
        if turl.lower().find('haoseed') :
            if len(turl) > 10:
                return turl[-10:]    
        if turl.lower().find('jandown') != -1 or turl.lower().index('mimima'):
            if len(turl) > 45:
                return turl[36:46]    
            
    def getSiteName(self,turl):
        if turl.lower().find('jandown') != -1:
            return 'http://www.jandown.com/'
        if turl.lower().find('mimima') != -1:
            return 'http://www.mimima.com/'     
        if turl.lower().find('haoseed') != -1:
            return 'http://www.haoseed.com/'     
        
    def getFetchUrl(self,turl):
        if self.siteName.find('haoseed') != -1:
            return self.siteName+'download.php'
        if self.siteName.find('jandown') != -1 or turl.lower().index('mimima'):
            return self.siteName+'fetch.php'

def getDownloadedFileName():
        return getId()+'.torrent'
        
def __download(pageUrl,proxy={}):
    info('downloading torrent from '+pageUrl)
    td = TorrentDownloader(pageUrl,proxy)
    filename = ''
    try :
        filename = td.download()
    except Exception:
        info('error downloading torrent file:'+str(pageUrl))
    info('Torrent downloaded')    
    return filename




if __name__ == '__main__':
    # import os
    # print os.path.getsize('../torrents/0x1bf588f668L-307d62e1-c75a-11dc-994b-00f0f43057f4.torrent')
    # post = Post.get(2)
    # for u in post.urls:
        # if u == None : continue
        # if canDownload(u.name) == True:
            # downloadForPost(post,u)
    testUrls = [
        '''http: //www6.mimima.com/link.php?ref=TFheYRHz1z'''    
        ,"http://www.jandown.com/link.php?ref=oLcbdoYSc8'target=_blank>http://www.jandown.com/link.php?ref=oLcbdoYSc8</a><br><br>东南亚白胖子，谁帮忙发出去<br></span><br>"
        ,'http://www.jandown.com/link.php?ref=pozJ5cXldI'
        ,'''http://pics.dmm.co.jp/mono/movie/h_254yume037/h_254yume037pl.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://pics.dmm.co.jp/mono/movie/h_254yume037/h_254yume037pl.jpg');"><br><br><imgsrc='http://i.pixs.ru/storage/0/4/3/3856312398_4590791_2096043.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.pixs.ru/storage/0/4/3/3856312398_4590791_2096043.jpg');"><br><br>LinkURL:<ahref='http://www.jandown.com/link.php?ref=2tRZtgu42Z'target=_blank>http://www.jandown.com/link.php?ref=2tRZtgu42Z</a><br>'''
        ,'''http://i.minus.com/ik50VrnSZLDlx.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/ik50VrnSZLDlx.jpg');"><br><br>　　<imgsrc='http://i.minus.com/iDnoLEtqOWI7a.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/iDnoLEtqOWI7a.jpg');"><br><br>　　<imgsrc='http://i.minus.com/iBpzcYtJXjwEi.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/iBpzcYtJXjwEi.jpg');"><br><br>　　<imgsrc='http://i.minus.com/iplv4IaApHrvJ.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/iplv4IaApHrvJ.jpg');"><br><br>　　<imgsrc='http://i.minus.com/iiJwbpzI7ZDgK.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/iiJwbpzI7ZDgK.jpg');"><br><br>　　<imgsrc='http://i.minus.com/i8rmu3GuGszEx.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/i8rmu3GuGszEx.jpg');"><br><br>　　<imgsrc='http://i.minus.com/iNdf7DMud7h8g.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/iNdf7DMud7h8g.jpg');"><br><br>　　<imgsrc='http://i.minus.com/iOoVFZPm3DdTi.jpg'border=0onclick="window.open('http://www2.lookpipe.com/get.php?filepath=http://i.minus.com/iOoVFZPm3DdTi.jpg');"><br><br>LinkURL:<ahref='http://www.jandown.com/link.php?ref=2RwLzeYdBf'target=_blank>http://www.jandown.com/link.php?ref=2RwLzeYdBf</a><br>BBCODE:<ahref='http://www.jandown.com/link.php?ref=2RwLzeYdBf'target=_blank>http://www.jandown.com/link.php?ref=2RwLzeYdBf</a><br></span><br>'''
        ,'http: //www6.mimima.com/link.php?ref=Y45Vtt5gZx<\/a><br><\/span><br>'
    
    ]
    for url in testUrls:
        if not canDownload(url):
            print 'FUCK'
        name, fl = TorrentDownloader(url).download('c:/temp')
        print name, fl
